const wordDao = require('../dao/wordDao'),
uwDao = require('../dao/urlWordDao'),
upt = require('../task/updatePTask');

module.exports = (sWord, resolve) => {
	var word = {
		word : sWord,
		p: 0
	}
	var p1 = new Promise(resolve => {
			wordDao.insert(word, () => {
				resolve(word)
			})
		}),
	p2 = new Promise(resolve => {
			wordDao.matchContainWord(sWord, words => {
				var selectUrlwordPromises = [];
				words.forEach(word => {
					selectUrlwordPromises.push(new Promise(resolve => {
							uwDao.matchWordId(word.wordId, uws => {
								resolve(uws)
							})
						}))
				})
				Promise.all(selectUrlwordPromises).then(uwss => {
					resolve(uwss)
				}).catch (err => {
					log(err)
				})
			})
		});
	Promise.all([p1, p2]).then(result => {
		var word = result[0],
		uwss = result[1],
		insertUrlwordPromises = [];
		uwss.forEach(uws => {
			uws.forEach(uw => {
				uw.wordId = word.wordId;
				insertUrlwordPromises.push(new Promise(resolve => {
						uwDao.insert(uw, () => {
							upt.add(uw, () => {
								resolve()
							})
						})
					}))
			})
		})
		Promise.all(insertUrlwordPromises).then(() => {
			resolve(word)
		}).catch (err => {
			log(err)
		})
	})
}
